const express = require('express')
const router = require('./router/router')
const cors = require('cors')
const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost/blog')

const app = express()

//引入插件
var vertoken = require('./token/token')
var expressJwt = require('express-jwt')

app.use(cors())
app.use('/public/', express.static('./public/'))
app.use(express.urlencoded({ extended: false }))
app.use(express.json())





// 解析token获取用户信息
app.use(function (req, res, next) {
  var token = req.headers['authorization'];
  if (token == undefined) {
    next();
  } else {
    vertoken.getToken(token).then((data) => {
      req.data = data;
      next();
    }).catch((error) => {
      next();
    })
  }
});



// 验证token是否过期并规定那些路由不需要验证
app.use(expressJwt({
  secret: 'jalksjdlanlkcnlakjslknencjoiqnlnlkjsalbbfbjasiuurdiwhejbjvhlasnkcvjoaisnenlkqjpripolwjetnljsdlkfhlvljslkdjflkjldskgnklsjdlkvjiuwijerlkwjenclksjdbabjsbdkjbqjkwherjwqhfrlnldskfnclkajd;lkjalksj2u301283saldfjhl21u38094lkajsldkjalskjdlkad',
  // 算法
  algorithms: ['HS256']
}).unless({
  path: ['/api/login', '/api/register', '/api/labels']  //不需要验证的接口名称
}))

//token失效返回信息
app.use(function (err, req, res, next) {
  if (err.status == 401) {
    return res.status(401).json({ msg: 'token失效', code: 401 })
  }
})

app.use(router)


app.listen(5000)